package Soul

import (
	codecs "sanguo/codec/cs"
	"sanguo/node/common/com_type"
	"sanguo/node/common/transaction"
	"sanguo/node/node_game"
	"sanguo/node/node_game/module/role"
	"sanguo/node/node_game/user"
	table_GamePlay "sanguo/node/table/excel/table/GamePlay"
	cs_message "sanguo/protocol/cs/message"
	"time"

	"github.com/golang/protobuf/proto"
)

type transactionSoulMoveLevel struct {
	transaction.TransactionBase
	user    *user.User
	req     *codecs.Message
	resp    *cs_message.SoulMoveLevelToC
	errcode cs_message.EnumType
}

func (this *transactionSoulMoveLevel) GetModuleName() string {
	return "Soul"
}

func (this *transactionSoulMoveLevel) GetReplyMsg() proto.Message {
	return &cs_message.SoulMoveLevelToC{}
}

func (this *transactionSoulMoveLevel) SetExpiredTime(expired time.Time) {
	this.Expired = expired
}

func (this *transactionSoulMoveLevel) GetExpiredTime() time.Time {
	return this.Expired
}

func (this *transactionSoulMoveLevel) Begin() {

	this.resp = &cs_message.SoulMoveLevelToC{}
	msg := this.req.GetData().(*cs_message.SoulMoveLevelToS)
	roleModule := this.user.GetModuleByName("role").(*role.RoleModule)
	role := roleModule.CurrentRole()
	if role == nil || !role.IsRoleModleData() {
		node_game.Infoln(role.GetUserID(), "SoulMoveLevel fail : role is nil")
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
		return
	}
	node_game.Infof("%s %d Call SoulMoveLevel fid:%d tid:%d", role.GetUserID(), role.GetID(), msg.GetFromSoulId(), msg.GetToSoulId())

	//验证功能开启
	if role.GetLev() < table_GamePlay.Table_.IDMap[com_type.GamePaly_Soul].UnlockLevel {
		node_game.Infoln(role.GetUserID(), role.GetID(), "Soul System is not Unlock")
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
		return
	}

	fromSoul := role.GetRoleSoul().GetSoul(msg.GetFromSoulId())
	toSoul := role.GetRoleSoul().GetSoul(msg.GetToSoulId())
	if toSoul == nil || fromSoul == nil {
		node_game.Infoln(role.GetUserID(), role.GetID(), "SoulMoveLevel fail:Soul is nil")
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
		return
	}

	role.GetRoleSoul().SoulMoveLevel(fromSoul, toSoul)

	//武魂为装备状态 重新计算战斗属性
	if role.GetRoleSoul().GetSoul(msg.GetToSoulId()).IsEquip || role.GetRoleSoul().GetSoul(msg.GetFromSoulId()).IsEquip {
		role.TotalBattleAttr()
	}

	node_game.Infoln(role.GetUserID(), role.GetID(), "SoulMoveLevel OK")
	this.errcode = cs_message.EnumType_OK
	this.user.EndTrans(this)
}

func (this *transactionSoulMoveLevel) End() {
	this.resp.Errcode = cs_message.EnumType(this.errcode).Enum()
	this.user.Reply(this.req.GetSeriNo(), this.resp)
}

func (this *transactionSoulMoveLevel) Timeout() {
	this.resp.Errcode = cs_message.EnumType(cs_message.EnumType_RETRY).Enum()
	this.user.EndTrans(this)
}

func init() {
	user.RegisterTransFunc(&cs_message.SoulMoveLevelToS{}, func(user *user.User, msg *codecs.Message) transaction.Transaction {
		return &transactionSoulMoveLevel{
			user: user,
			req:  msg,
		}
	})
}
